package data.strategydata;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import po.FacultyTeacherPO;
import po.Institute;
import po.StrategyPO;
import dataservice.strategydataservice.StrategyDataService;

public class StrategyData extends UnicastRemoteObject implements
		StrategyDataService {

	PreparedStatement ps = null;
	Connection ct = null;
	ResultSet rs = null;

	public StrategyData() throws RemoteException {
	}

	@Override
	public void init() {
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			ct = DriverManager.getConnection("jdbc:odbc:CourseSelectionSystem");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		try {
			if (ps != null) {
				ps.close();
			}
			if (ct != null) {
				ct.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean update(StrategyPO po) {
		int[] totalCredit = po.getTotalCredit();
		init();
		try {
			for (int j = 0; j < totalCredit.length; j++) {
				String sql = "update Strategy set totalCredit="
						+ totalCredit[j] + " where no=" + j;
				ps = ct.prepareStatement(sql);
				int i = ps.executeUpdate();
				if (i != 1) {
					finish();
					return false;
				}

			}
			finish();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public StrategyPO find() {
		int[] totalCredit = new int[8];
		init();
		try {
			String sql = "select * from Strategy";
			ps = ct.prepareStatement(sql);
			rs = ps.executeQuery();
			int i=0;
			while (rs.next()) {
				totalCredit[i]=rs.getInt(2);
				i++;
			}
			if (rs != null) {
				rs.close();
			}
			finish();
		} catch (SQLException e) {
			return null;
		}
		StrategyPO po = new StrategyPO(totalCredit);
		return po;
	}

}
